package com.hitqz.robot.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.common.entity.RobotMap;
import com.hitqz.robot.api.common.entity.RobotMapPos;
import com.hitqz.robot.api.dispatch.protocol.dto.RobotMapPosDto;
import com.hitqz.robot.biz.mapper.RobotMapPosMapper;
import com.hitqz.robot.biz.service.RobotMapPosService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.driver.model.PointDto;
import com.hitqz.robot.driver.parent.RobotDriverService;
import com.hitqz.robot.netty.service.Send2ServerService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xupkun
 * @date 2024/5/29
 */
@Service
@AllArgsConstructor

public class RobotMapPosServiceImpl extends ServiceImpl<RobotMapPosMapper, RobotMapPos> implements RobotMapPosService {

    private final Send2ServerService send2ServerService;

    private final RobotService robotService;

    private final RobotDriverService robotDriver;

    private final RobotMapServiceImpl robotMapService;

    @Override
    public void syncMapPos() {
        List<RobotMapPos> robotMapPosList = baseMapper.selectList(null);
        if (CollectionUtil.isNotEmpty(robotMapPosList)) {
            Robot robot = robotService.getDefaultRobot();
            RobotMap map = robotMapService.getOne(Wrappers.<RobotMap>lambdaQuery().eq(RobotMap::getMapCode, robot.getMapCode()).last("limit 1"));
            robotMapPosList.forEach(pos-> {
                try{
                    PointDto pointDto = robotDriver.point2Canvas(map, new PointDto(pos.getPosX(), pos.getPosY()));
                    if (pointDto != null){
                        pos.setPixelX(Double.valueOf(pointDto.getX()).intValue());
                        pos.setPixelY(Double.valueOf(pointDto.getY()).intValue());
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                RobotMapPosDto robotMapPosDto = new RobotMapPosDto();
                BeanUtil.copyProperties(pos, robotMapPosDto, false);
                robotMapPosDto.setClientId(robot.getRobotSn());
                send2ServerService.syncRobotMapPosInfo(0, robotMapPosDto);
            });
            //更新像素坐标
            updateBatchById(robotMapPosList);
        }
    }
}
